import json 
import urllib.request
import urllib.parse

def translate():
    #定义需要爬取的链接地址和参数
    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
    key = input("请输入要翻译的内容：")

    #定义表单
    data = {
        'i': str(key),
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': '15711215086542',
        'sign': 'c43304764330314a0cdea69325e832a4',
        'ts': '1571121508654',
        'bv': 'f4d62a2579ebb44874d7ef93ba47e822',
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTlME'
    }
    data = urllib.parse.urlencode(data).encode("utf-8")#python本身字符串是Unicode，需要转换成网页默认的utf-8

    #设置头文件
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}

    #执行爬取操作
    req = urllib.request.Request(url=url,data=data,headers=headers)
    res = urllib.request.urlopen(req)

    #执行数据解析 str_json = res.read().decode("utf-8") my_json = json.load(str_json)
    str_json = res.read().decode("utf-8")
    my_json = json.loads(str_json)
    print("翻译结果为:%s" %(my_json['translateResult'][0][0]['tgt']))

if __name__ == '__main__':
    while True:
        translate()